package pro.shushi.pamirs.hr.core.manager.auth;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import pro.shushi.pamirs.auth.api.runtime.session.AuthRoleSession;
import pro.shushi.pamirs.auth.api.utils.AuthFetchPermissionHelper;
import pro.shushi.pamirs.core.common.path.ResourcePathParser;
import pro.shushi.pamirs.framework.connectors.data.sql.Pops;
import pro.shushi.pamirs.hr.api.model.auth.AppAuthResource;
import pro.shushi.pamirs.hr.api.tmodel.AuthResourceTransient;
import pro.shushi.pamirs.meta.annotation.fun.extern.Slf4j;
import pro.shushi.pamirs.meta.api.Models;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author shushi
 */
@Slf4j
@Service
public class AuthResourceManager {

    @Autowired
    private ResourcePathParser resourcePathParser;

    public List<AppAuthResource> fetchActionPermissions() {
        Set<Long> roleIds = AuthRoleSession.getCurrentRoles();
        Set<String> result = new HashSet<>();
        AuthFetchPermissionHelper.mergeModelActionPermissions(result, roleIds, AuthResourceTransient.MODEL_MODEL);
        if (CollectionUtils.isEmpty(result)) {
            return new ArrayList<>();
        }

        List<String> actionNames = new ArrayList<>();
        result.forEach(path -> {
            String actionName = getLastPartAfterLastSlash(path);
            if (StringUtils.isNotEmpty(actionName)) {
                actionNames.add(actionName);
            }
        });

        return Models.origin().queryListByWrapper(Pops.<AppAuthResource>lambdaQuery().from(AppAuthResource.MODEL_MODEL).setBatchSize(-1)
                .in(AppAuthResource::getResUnique, actionNames));
    }

    /**
     * 获取最后一个斜杠后的部分。
     *
     * @param input 输入字符串
     * @return 最后一个斜杠后的部分
     */
    public static String getLastPartAfterLastSlash(String input) {
        if (input == null || input.isEmpty()) {
            return "";
        }
        int lastSlashIndex = input.lastIndexOf('/');
        return input.substring(lastSlashIndex + 1);
    }

}
